<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="上传图片, wujie">
    <meta name="description" content="无解的技术博客">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>上传图片 | 无解</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">无解</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">无解</div>
        <div class="logo-desc">
            
            无解的技术博客
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/7.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">上传图片</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
        
        position: absolute;
        right: 23.5vw;
        display: block;
    }

    .toc-fixed .toc-link::before{
        position: fixed!important;/*当toc的位置改为fixed时，.toc-link::before也要改为fixed*/
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Laravel/">
                                <span class="chip bg-color">Laravel</span>
                            </a>
                        
                            <a href="/tags/ThinkPHP/">
                                <span class="chip bg-color">ThinkPHP</span>
                            </a>
                        
                            <a href="/tags/JavaScript/">
                                <span class="chip bg-color">JavaScript</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Share/" class="post-category">
                                Share
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-04-06
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2020-04-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2k
                </div>
                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="Laravel异步上传流程一"><a href="#Laravel异步上传流程一" class="headerlink" title="Laravel异步上传流程一"></a>Laravel异步上传流程一</h2><ol>
<li>产生异步的请求</li>
<li>请求得有一个相应的方法（需要返回值，返回内容：图片的路径；在此不需要进行数据表的交互）</li>
<li>当异步请求获取到相应之后需要存储图片的地址（但是又没必要给用户看地址，可以使用隐藏域的方式进行存储）</li>
<li>当用户提交表单的时候，顺带提交隐藏域的地址</li>
</ol>
<h3 id="laravel-实现上传处理方法"><a href="#laravel-实现上传处理方法" class="headerlink" title="laravel 实现上传处理方法"></a>laravel 实现上传处理方法</h3><blockquote>
<p>在 laravel 项目中除了在上传的时候可以使用 move 和 store 方法【都是 request 实例封装的】之外，还可以使用高级的上传文件保存方法 (由 storage 门面提供的)</p>
</blockquote>
<p><strong>Storage 门面在使用的时候需要的注意事项：</strong></p>
<ul>
<li>在 storage 门面中，有一个 “磁盘” 的概念，“磁盘” 一共有三种：<strong>本地磁盘，公共磁盘</strong>，第三方磁盘；“磁盘” 实质上就是一个目录</li>
<li>本地磁盘 (local 磁盘)，这些文件存放在 local 磁盘中的文件是<strong>不能被浏览器访问到的</strong>，存储在其中的文件一般都是项目的 php 代码自身使用！（磁盘位置位于 / Storage/app）</li>
<li>公共磁盘 (public 磁盘)，存储在该磁盘的文件一般是<strong>允许浏览器进行访问的</strong>。【磁盘位置位于：/Storage/app/public】</li>
<li>第三方磁盘：驱动形式的一种，允许开发者将文件上传到第三方的服务器上。</li>
<li>磁盘存在一个配置文件，位置 /config/filesystems.php</li>
</ul>
<p><strong>默认情况下，浏览器是无法访问到 public 磁盘目录的，但是其又想让浏览器访问，所以需要做一个 “软链接的 “的操作”</strong></p>
<pre class=" language-javascript"><code class="language-javascript">php artisan storage<span class="token punctuation">:</span>link</code></pre>
<p><strong>相当于快捷方式</strong></p>
<blockquote>
<p>当软链接创建好之后，Public 磁盘中的内容会被同步到 /public/storage/ 下</p>
<p>Storage 门面的通用文件保存方法：</p>
</blockquote>
<pre class=" language-javascript"><code class="language-javascript">Storage<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token function">disk</span><span class="token punctuation">(</span>磁盘名<span class="token punctuation">)</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">put</span><span class="token punctuation">(</span>文件名，文件内容<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h3 id="异步请求回调处理"><a href="#异步请求回调处理" class="headerlink" title="异步请求回调处理"></a>异步请求回调处理</h3><p><em>在 html 代码中添加隐藏域</em></p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token operator">&lt;</span>input type<span class="token operator">=</span><span class="token string">"hidden"</span> name<span class="token operator">=</span><span class="token string">"avatar"</span> value<span class="token operator">=</span><span class="token string">""</span><span class="token operator">></span></code></pre>
<p>通过回调将返回的 path 写入隐藏域</p>
<h3 id="使用七牛云存储存储文件"><a href="#使用七牛云存储存储文件" class="headerlink" title="使用七牛云存储存储文件"></a>使用七牛云存储存储文件</h3><blockquote>
<p>七牛：一家提供各种网络服务的运营商，其性质类似于阿里云</p>
<p>做到代码与资源分离</p>
<p><strong>原因：</strong></p>
<ol>
<li><strong>在后期维护网站的也比较方便；</strong></li>
<li><strong>资源分离之后可以减轻代码服务器的压力；</strong></li>
<li><strong>如何将资源分离和 CDN (content delivery network 内容分发网络) 配合起来用，对于 bat 之类的大公司来说 1 年能够生下来的成本至少 7 位数以上；</strong></li>
</ol>
</blockquote>
<p><strong>注册七牛账号后创建后期需要的对象存储实例 (不用充钱，每月免费 10G 空间， 20G 的流量)</strong></p>
<ul>
<li><p>选择对象存储</p>
</li>
<li><p>新建空间：自己在哪个区域选择哪个存储区域</p>
</li>
<li><p>下载七牛的代码依赖库</p>
<ul>
<li><pre class=" language-php"><code class="language-php">composer <span class="token keyword">require</span> zgldh<span class="token operator">/</span>qiniu<span class="token operator">-</span>laravel<span class="token operator">-</span>storage</code></pre>
</li>
<li><p>配置 filesystems.php：</p>
</li>
<li><pre class=" language-javascript"><code class="language-javascript"><span class="token string">'qiiniu'</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">[</span>
          <span class="token string">'driver'</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token string">'qiniu'</span><span class="token punctuation">,</span>
          <span class="token string">'domains'</span><span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">[</span>
              <span class="token string">'default'</span>   <span class="token operator">=</span><span class="token operator">></span> <span class="token string">'xxxx.com1.z0.glb.clouddn.com'</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true">// 你的七牛域名</span>
              <span class="token string">'https'</span>     <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span><span class="token punctuation">,</span>
              <span class="token string">'custom'</span>    <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span>
          <span class="token punctuation">]</span><span class="token punctuation">,</span>
          <span class="token string">'access_key'</span>    <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true">// AK</span>
          <span class="token string">'secret_key'</span>    <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true">// SK</span>
          <span class="token string">'bucket'</span>        <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true">// 磁盘名字</span>
          <span class="token string">'notify_url'</span>    <span class="token operator">=</span><span class="token operator">></span> <span class="token string">''</span><span class="token punctuation">,</span>  <span class="token comment" spellcheck="true">// 持久化处理</span>
          <span class="token string">'access'</span>        <span class="token operator">=</span><span class="token operator">></span> <span class="token string">'public'</span><span class="token punctuation">,</span>    <span class="token comment" spellcheck="true">// 空间访问控制</span>
      <span class="token punctuation">]</span><span class="token punctuation">,</span></code></pre>
</li>
<li><p>添加 providers 数组：</p>
</li>
<li><pre class=" language-javascript"><code class="language-javascript">zgldh\QiniuStorage\QiniuFilesystemServiceProvider<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token keyword">class</span><span class="token punctuation">,</span></code></pre>
</li>
</ul>
</li>
</ul>
<h2 id="Laravel存储用户上传图片的方法二"><a href="#Laravel存储用户上传图片的方法二" class="headerlink" title="Laravel存储用户上传图片的方法二"></a>Laravel存储用户上传图片的方法二</h2><p>本项目中，我们不止上传头像需要用到『图片上传功能』，在后面发布帖子功能中，我们也将会允许用户上传图片，所以此处我们需要预先设计一下图片上传相关的逻辑，我们可以将『图片上传』核心操作做成一个工具类（注意顶部 <code>use Illuminate\Support\Str;</code>）：</p>
<p><em>app/Handlers/ImageUploadHandler.php</em></p>
<pre class=" language-php"><code class="language-php"><span class="token delimiter">&lt;?php</span>

<span class="token keyword">namespace</span> <span class="token package">App<span class="token punctuation">\</span>Handlers</span><span class="token punctuation">;</span>

<span class="token keyword">use</span>  <span class="token package">Illuminate<span class="token punctuation">\</span>Support<span class="token punctuation">\</span>Str</span><span class="token punctuation">;</span>

<span class="token keyword">class</span> <span class="token class-name">ImageUploadHandler</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 只允许以下后缀名的图片文件上传</span>
    <span class="token keyword">protected</span> <span class="token variable">$allowed_ext</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"png"</span><span class="token punctuation">,</span> <span class="token string">"jpg"</span><span class="token punctuation">,</span> <span class="token string">"gif"</span><span class="token punctuation">,</span> <span class="token string">'jpeg'</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function">save</span><span class="token punctuation">(</span><span class="token variable">$file</span><span class="token punctuation">,</span> <span class="token variable">$folder</span><span class="token punctuation">,</span> <span class="token variable">$file_prefix</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 构建存储的文件夹规则，值如：uploads/images/avatars/201709/21/</span>
        <span class="token comment" spellcheck="true">// 文件夹切割能让查找效率更高。</span>
        <span class="token variable">$folder_name</span> <span class="token operator">=</span> <span class="token string">"uploads/images/$folder/"</span> <span class="token punctuation">.</span> <span class="token function">date</span><span class="token punctuation">(</span><span class="token string">"Ym/d"</span><span class="token punctuation">,</span> <span class="token function">time</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 文件具体存储的物理路径，`public_path()` 获取的是 `public` 文件夹的物理路径。</span>
        <span class="token comment" spellcheck="true">// 值如：/home/vagrant/Code/larabbs/public/uploads/images/avatars/201709/21/</span>
        <span class="token variable">$upload_path</span> <span class="token operator">=</span> <span class="token function">public_path</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">.</span> <span class="token string">'/'</span> <span class="token punctuation">.</span> <span class="token variable">$folder_name</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 获取文件的后缀名，因图片从剪贴板里黏贴时后缀名为空，所以此处确保后缀一直存在</span>
        <span class="token variable">$extension</span> <span class="token operator">=</span> <span class="token function">strtolower</span><span class="token punctuation">(</span><span class="token variable">$file</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">getClientOriginalExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">?</span><span class="token punctuation">:</span> <span class="token string">'png'</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 拼接文件名，加前缀是为了增加辨析度，前缀可以是相关数据模型的 ID </span>
        <span class="token comment" spellcheck="true">// 值如：1_1493521050_7BVc9v9ujP.png</span>
        <span class="token variable">$filename</span> <span class="token operator">=</span> <span class="token variable">$file_prefix</span> <span class="token punctuation">.</span> <span class="token string">'_'</span> <span class="token punctuation">.</span> <span class="token function">time</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">.</span> <span class="token string">'_'</span> <span class="token punctuation">.</span> Str<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">.</span> <span class="token string">'.'</span> <span class="token punctuation">.</span> <span class="token variable">$extension</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 如果上传的不是图片将终止操作</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span> <span class="token operator">!</span> <span class="token function">in_array</span><span class="token punctuation">(</span><span class="token variable">$extension</span><span class="token punctuation">,</span> <span class="token variable">$this</span><span class="token operator">-</span><span class="token operator">></span><span class="token property">allowed_ext</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">// 将图片移动到我们的目标存储路径中</span>
        <span class="token variable">$file</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">move</span><span class="token punctuation">(</span><span class="token variable">$upload_path</span><span class="token punctuation">,</span> <span class="token variable">$filename</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> <span class="token punctuation">[</span>
            <span class="token string">'path'</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">config</span><span class="token punctuation">(</span><span class="token string">'app.url'</span><span class="token punctuation">)</span> <span class="token punctuation">.</span> <span class="token string">"/$folder_name/$filename"</span>
        <span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>我们将使用 <code>app/Handlers</code> 文件夹来存放本项目的工具类，『工具类（utility class）』是指一些跟业务逻辑相关性不强的类，<code>Handlers</code> 意为 <strong>处理器</strong> ，ImageUploadHandler 意为图片上传处理器，简单易懂。</p>
<pre class=" language-php"><code class="language-php">`<span class="token function">public_path</span><span class="token punctuation">(</span><span class="token punctuation">)</span>` 获取的是 `<span class="token keyword">public</span>` 文件夹的物理路径。</code></pre>
<blockquote>
<p>这里写了一个图片上传处理类，方便网站各处需要上传图片的进行调用</p>
<p>调用呢，成功则返回图片的地址，开发者接收到图片的地址后，哪怕是在页面显示图片，或者在表单里进行添加入库，都提供了方便。</p>
</blockquote>
<h2 id="ThinkPHP6-0版本的上传图片操作"><a href="#ThinkPHP6-0版本的上传图片操作" class="headerlink" title="ThinkPHP6.0版本的上传图片操作"></a>ThinkPHP6.0版本的上传图片操作</h2><blockquote>
<p>基于上面Laravel开发的图片上传处理类，我将之进行整改，适合TP6的</p>
</blockquote>
<pre class=" language-php"><code class="language-php"><span class="token keyword">use</span> <span class="token package">think<span class="token punctuation">\</span>facade<span class="token punctuation">\</span>Filesystem</span><span class="token punctuation">;</span>

<span class="token keyword">class</span> <span class="token class-name">ImageUploadHandle</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 只允许以下后缀的图片文件</span>
    <span class="token keyword">protected</span> <span class="token variable">$allowed_ext</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"png"</span><span class="token punctuation">,</span> <span class="token string">"jpg"</span><span class="token punctuation">,</span> <span class="token string">"gif"</span><span class="token punctuation">,</span> <span class="token string">'jpeg'</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/**
     * @param $file
     * @param $folder
     * @param bool $fileas 默认为false，保存到public目录下的指定目录格式下；为true，保存到public下的指定目录下
     * @return bool|string
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function">save</span><span class="token punctuation">(</span><span class="token variable">$file</span><span class="token punctuation">,</span> <span class="token variable">$folder</span><span class="token punctuation">,</span> <span class="token variable">$fileas</span> <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token variable">$file</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">// 获取文件后缀</span>
            <span class="token variable">$extension</span> <span class="token operator">=</span> <span class="token function">strtolower</span><span class="token punctuation">(</span><span class="token variable">$file</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">extension</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment" spellcheck="true">// 如果上传的不是图片终止操作</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">in_array</span><span class="token punctuation">(</span><span class="token variable">$extension</span><span class="token punctuation">,</span> <span class="token variable">$this</span><span class="token operator">-</span><span class="token operator">></span><span class="token property">allowed_ext</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                <span class="token variable">$savename</span> <span class="token operator">=</span> <span class="token variable">$fileas</span> <span class="token operator">==</span> <span class="token boolean">false</span>
                    <span class="token operator">?</span> Filesystem<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token function">disk</span><span class="token punctuation">(</span><span class="token string">'public'</span><span class="token punctuation">)</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">putFile</span><span class="token punctuation">(</span><span class="token variable">$folder</span><span class="token punctuation">,</span> <span class="token variable">$file</span><span class="token punctuation">)</span>
                    <span class="token punctuation">:</span> Filesystem<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token function">disk</span><span class="token punctuation">(</span>
                        <span class="token string">'public'</span>
                    <span class="token punctuation">)</span>
                        <span class="token operator">-</span><span class="token operator">></span><span class="token function">putFileAs</span><span class="token punctuation">(</span><span class="token variable">$folder</span><span class="token punctuation">.</span><span class="token string">'/'</span><span class="token punctuation">.</span><span class="token function">date</span><span class="token punctuation">(</span><span class="token string">'Ymd'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token variable">$file</span><span class="token punctuation">,</span> <span class="token variable">$file</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">getOriginalName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name"><span class="token punctuation">\</span>Exception</span> <span class="token variable">$e</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">return</span> <span class="token variable">$e</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token variable">$savename</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TP6中获取图片路径的方法</span>
                <span class="token variable">$path</span> <span class="token operator">=</span> Filesystem<span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token function">getDiskConfig</span><span class="token punctuation">(</span><span class="token string">'public'</span><span class="token punctuation">,</span> <span class="token string">'url'</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token string">'/'</span><span class="token punctuation">.</span><span class="token function">str_replace</span><span class="token punctuation">(</span><span class="token string">'\\'</span><span class="token punctuation">,</span> <span class="token string">'/'</span><span class="token punctuation">,</span> <span class="token variable">$savename</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">return</span> <span class="token variable">$path</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>这样会保存到<code>public/storage/自己定义的目录</code>下</p>
<p>对应的html页面:</p>
<pre class=" language-html"><code class="language-html"> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>{$admin_info.avatar|default<span class="token punctuation">=</span><span class="token punctuation">'</span>/static/admin/img/logo.png<span class="token punctuation">'</span>}<span class="token punctuation">"</span></span> <span class="token attr-name">alt</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>选择并上传头像<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>avatar_img<span class="token punctuation">"</span></span><span class="token style-attr language-css"><span class="token attr-name"> <span class="token attr-name">style</span></span><span class="token punctuation">="</span><span class="token attr-value"><span class="token property">width</span><span class="token punctuation">:</span> <span class="token number">140</span>px<span class="token punctuation">;</span><span class="token property">height</span><span class="token punctuation">:</span> <span class="token number">140</span>px<span class="token punctuation">;</span><span class="token property">left</span><span class="token punctuation">:</span><span class="token number">0</span><span class="token punctuation">;</span><span class="token property">top</span><span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">;</span><span class="token property">border-radius</span><span class="token punctuation">:</span> <span class="token number">50%</span><span class="token punctuation">;</span></span><span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>file<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>avatar<span class="token punctuation">"</span></span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>avatar<span class="token punctuation">"</span></span> <span class="token attr-name">accept</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>image/jpg,image/png,image/gif<span class="token punctuation">"</span></span><span class="token style-attr language-css"><span class="token attr-name"> <span class="token attr-name">style</span></span><span class="token punctuation">="</span><span class="token attr-value"><span class="token property">width</span><span class="token punctuation">:</span> <span class="token number">100%</span><span class="token punctuation">;</span><span class="token property">height</span><span class="token punctuation">:</span><span class="token number">100%</span><span class="token punctuation">;</span><span class="token property">opacity</span><span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">;</span><span class="token property">position</span><span class="token punctuation">:</span> absolute<span class="token punctuation">;</span><span class="token property">left</span><span class="token punctuation">:</span><span class="token number">0</span><span class="token punctuation">;</span><span class="token property">top</span><span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">;</span></span><span class="token punctuation">"</span></span> <span class="token attr-name">onchange</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>uploadImg(this)<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre>
<ul>
<li><code>{$admin_info}</code>：这是后端进行查询单个管理员信息的数组</li>
<li><code>{$admin_info.avatar|default=&#39;/static/admin/img/logo.png&#39;}</code>：代表如果这个管理员存在头像，就显示自己的头像，没有则显示默认的一个图片的地址</li>
<li>真正点击上传头像的还是下面的<code>input</code>中的<code>onchange</code>事件调用<code>uploadImg(this)</code>方法</li>
<li><code>this</code>代表当前<code>html</code>组件<code>input</code></li>
</ul>
<p><code>ajax</code>方法上传代码:</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">uploadImg</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>obj<span class="token punctuation">.</span>value <span class="token operator">===</span> <span class="token string">""</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">let</span> formData <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FormData</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        formData<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token string">"avatar"</span><span class="token punctuation">,</span> <span class="token function">$</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>files<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        $<span class="token punctuation">.</span><span class="token function">ajax</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            type<span class="token punctuation">:</span> <span class="token string">"POST"</span><span class="token punctuation">,</span>
            url<span class="token punctuation">:</span> <span class="token string">"/admin/Admin/uploadAvatar"</span><span class="token punctuation">,</span>
            data<span class="token punctuation">:</span> formData<span class="token punctuation">,</span>
            cache<span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
            processData<span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
            contentType<span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
            success<span class="token punctuation">:</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// 接收返回的图片地址</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>data<span class="token punctuation">.</span>code <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    toastr<span class="token punctuation">.</span><span class="token function">success</span><span class="token punctuation">(</span><span class="token string">"上传头像"</span><span class="token punctuation">,</span> data<span class="token punctuation">.</span>msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token comment" spellcheck="true">// 设置图片路径为最新的路径</span>
                    <span class="token function">$</span><span class="token punctuation">(</span><span class="token string">"#avatar_img"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">attr</span><span class="token punctuation">(</span><span class="token string">"src"</span><span class="token punctuation">,</span> data<span class="token punctuation">.</span>data<span class="token punctuation">.</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        location<span class="token punctuation">.</span>href <span class="token operator">=</span> <span class="token string">"/admin/Admin/profile"</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                    toastr<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span>data<span class="token punctuation">.</span>msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span></code></pre>
<blockquote>
<p><code>FormData</code>是<code>js</code>的一个东西，通过这个将上传的文件获取到并<code>append</code>到<code>formData</code>实例中</p>
<p>然后通过<code>ajax</code>进行图片上传</p>
</blockquote>
<p>后端处理代码:</p>
<blockquote>
<p>通过依赖注入将<code>Request</code> and <code>ImageUploadHandle</code>进行注入</p>
<p>将文件处理类获取的返回的图片地址保存到表中</p>
</blockquote>
<pre class=" language-php"><code class="language-php"><span class="token comment" spellcheck="true">/**
     * 上传头像
     * @param Request $request
     * @param ImageUploadHandle $imageUploadHandle
     * @return \think\response\Json
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function">uploadAvatar</span><span class="token punctuation">(</span>Request <span class="token variable">$request</span><span class="token punctuation">,</span> ImageUploadHandle <span class="token variable">$imageUploadHandle</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token variable">$request</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">isPost</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token operator">!</span><span class="token variable">$request</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">isAjax</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token function">writeJson</span><span class="token punctuation">(</span><span class="token function">config</span><span class="token punctuation">(</span><span class="token string">'status.error'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"请求类型不合法"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token variable">$avatar</span> <span class="token operator">=</span> <span class="token variable">$request</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">file</span><span class="token punctuation">(</span><span class="token string">'avatar'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token variable">$path</span>   <span class="token operator">=</span> <span class="token variable">$imageUploadHandle</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">save</span><span class="token punctuation">(</span><span class="token variable">$avatar</span><span class="token punctuation">,</span> <span class="token string">'avatar'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 将路径存储进入表中</span>
        <span class="token comment" spellcheck="true">// 获取当前用户id</span>
        <span class="token variable">$admin_id</span> <span class="token operator">=</span> <span class="token function">session</span><span class="token punctuation">(</span><span class="token string">'session_admin.id'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token variable">$result</span> <span class="token operator">=</span> <span class="token variable">$this</span><span class="token operator">-</span><span class="token operator">></span><span class="token property">adminService</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">saveAvatar</span><span class="token punctuation">(</span><span class="token variable">$admin_id</span><span class="token punctuation">,</span> <span class="token variable">$path</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name"><span class="token punctuation">\</span>Exception</span> <span class="token variable">$e</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token function">writeJson</span><span class="token punctuation">(</span><span class="token function">config</span><span class="token punctuation">(</span><span class="token string">'status.error'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token variable">$e</span><span class="token operator">-</span><span class="token operator">></span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token variable">$data</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'path'</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token variable">$path</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token variable">$result</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token function">writeJson</span><span class="token punctuation">(</span><span class="token function">config</span><span class="token punctuation">(</span><span class="token string">'status.success'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"头像上传成功"</span><span class="token punctuation">,</span> <span class="token variable">$data</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">return</span> <span class="token function">writeJson</span><span class="token punctuation">(</span><span class="token function">config</span><span class="token punctuation">(</span><span class="token string">'status.error'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"上传失败"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span></code></pre>
<p>上传结束后，使用<code>js</code>来实现预览效果：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// 头像预览</span>
    <span class="token function">$</span><span class="token punctuation">(</span><span class="token string">"#avatar"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">change</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 获取上传文件对象</span>
        <span class="token keyword">var</span> file <span class="token operator">=</span> <span class="token function">$</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>files<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 读取文件URL</span>
        <span class="token keyword">var</span> reader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileReader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        reader<span class="token punctuation">.</span><span class="token function">readAsDataURL</span><span class="token punctuation">(</span>file<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 阅读文件完成后触发的事件</span>
        reader<span class="token punctuation">.</span>onload <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">// 读取的URL结果：this.result</span>
            <span class="token function">$</span><span class="token punctuation">(</span><span class="token string">"#avatar_img"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">attr</span><span class="token punctuation">(</span><span class="token string">"src"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://wxvirus.gitee.io" rel="external nofollow noreferrer">virus</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://wxvirus.gitee.io/2020/04/06/%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87/">http://wxvirus.gitee.io/2020/04/06/%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="http://wxvirus.gitee.io" target="_blank">virus</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Laravel/">
                                    <span class="chip bg-color">Laravel</span>
                                </a>
                            
                                <a href="/tags/ThinkPHP/">
                                    <span class="chip bg-color">ThinkPHP</span>
                                </a>
                            
                                <a href="/tags/JavaScript/">
                                    <span class="chip bg-color">JavaScript</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/04/07/ThinkPHP5-1%E6%B8%85%E9%99%A4%E7%BC%93%E5%AD%98%E5%8A%9F%E8%83%BD%E7%9A%84%E5%AE%9E%E7%8E%B0/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/22.jpg" class="responsive-img" alt="ThinkPHP5.1清除缓存功能的实现">
                        
                        <span class="card-title">ThinkPHP5.1清除缓存功能的实现</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            ThinkPHP5.1 清除缓存第一种方法
在基类控制器里，写上clear()方法，到时候用于调用,在也不是JS里alert(&#39;清除缓存了&#39;)当然，5.1取消了CACHE_PATH TEMP_PATH常量，所以要定义这些缓存
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-04-07
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/PHP/">
                        <span class="chip bg-color">PHP</span>
                    </a>
                    
                    <a href="/tags/ThinkPHP/">
                        <span class="chip bg-color">ThinkPHP</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/04/05/ThinkPHP%E5%B8%B8%E7%94%A8%E7%9A%84%E5%85%AC%E5%85%B1%E5%87%BD%E6%95%B0/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="ThinkPHP常用的公共函数">
                        
                        <span class="card-title">ThinkPHP常用的公共函数</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            自定义返回json格式的输出函数参数：



参数名
必选
类型
说明



code
是
int
返回码


msg
是
string
返回信息 default=”error”


data
否
array
返回的数据


httpSta
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-04-05
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/PHP/">
                        <span class="chip bg-color">PHP</span>
                    </a>
                    
                    <a href="/tags/ThinkPHP/">
                        <span class="chip bg-color">ThinkPHP</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 无解<br />'
            + '文章作者: Virus<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="http://wxvirus.gitee.io" target="_blank">Virus</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">34.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinwangqilin" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1418667580@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1418667580" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1418667580" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
